<template lang="pug">
data-page(
  v-bind="pageParams"
)
  mt-table(
    v-bind="tableProps"
  )

  edit-form(
    v-bind="editFormProps"
  )
ProjectAssociationList(v-model="modelValue" :selectEquipment="props.selectEquipment" @message-to-parent="request('tableData')")
</template>

<script setup lang="ts">
import {
  type FormItemProps,
  type IAction,
  type DataPageProps,
  type Action,
  type EditFormProps,
  type TableProps,
  useNotify,
} from "@scmt/common-components";
import { type QueryPagination, useApi } from "@scmt/core-api";
import type {
  PortfolioProjectEntity,
  PortfolioProjectQueryParams,
} from "@scmt/api-lis-portfolio-project";
import { type EquipmentEntity } from "@scmt/api-lis-equipment";
import ProjectAssociationList from "./ProjectAssociationList.vue";
import { useRequest } from "@scmt/common-hooks";

const $api = useApi();
const $notify = useNotify();
const modelValue = ref<Boolean>(false);
const queryPramas = reactive<PortfolioProjectQueryParams>({
  pageNum: 1,
  pageSize: 20,
});
const editingObj = ref<null | PortfolioProjectEntity>(null);

//添加 Props属性
const props = defineProps({
  selectEquipment: {
    type: Object as PropType<EquipmentEntity>,
    default: () => {},
  },
});

const { request, data, loadingMap } = useRequest({
  tableData: (q: any) => {
    let params = Object.assign(
      { deviceId: props.selectEquipment?.value?.id },
      queryPramas,
      q
    );
    if (!props.selectEquipment || !props.selectEquipment.id) {
      $notify.warning("请先选择设备字典");
      //没有选择设备的话 deviceId传一个不会有的值
      params = Object.assign({ deviceId: "testtt" }, queryPramas, q);
    } else {
      params = Object.assign(
        {
          deviceId: props.selectEquipment?.id,
        },
        queryPramas,
        q
      );
    }
    return $api.lis.portfolioProject.getRelatedDeviceIdProjectListByPage(
      params
    );
  },
  cancelDeviceRelatedPortfolioProjects: (params: any) => {
    return $api.lis.portfolioInstrument
      .cancelDeviceRelatedPortfolioProjects(params)
      .then(() => {
        $notify.success("取消关联成功");
        request("tableData");
      });
  },
  save: (model: PortfolioProjectEntity) => {
    return $api.lis.portfolioProject.save(model).then(() => {
      $notify.success("保存成功");
      editingObj.value = null;

      request("tableData", {
        pageNum: 1,
        pageSize: 20,
      });
    });
  },
  destroy: (ids: string) => {
    return $api.lis.portfolioProject.destroy(ids).then(() => {
      $notify.success("删除成功");

      request("tableData", {
        pageSize: 1,
      });
    });
  },
  listAsOptions: () => {
    return $api.lis.tube.listAsOptions();
  },
  listcategoryOptions: () => {
    return $api.lis.specimen.category.listAsOptions();
  },
});

const pageParams = computed<DataPageProps>(() => {
  const queryFields: FormItemProps[] = [
    {
      prop: "name",
      label: "项目名称",
    },
  ];

  const headerActions: Action[] = [
    { event: "relation", label: "批量关联", type: "primary" },
  ];

  const dataPageProps: DataPageProps = {
    loading: loadingMap.tableData,
    queryModel: queryPramas,
    queryFields,
    actions: headerActions,
    onQuery: () => request("tableData"),
    columns: 4,
    onAct: onPageActions,
  };

  return dataPageProps;
});

const tableProps = computed(() => {
  const { tableData } = toRefs(data);

  const tableProps: TableProps = {
    loading: loadingMap.tableData,
    data: tableData.value?.items,
    pagination: tableData.value?.pagination,
    columns: [
      {
        type: "index",
        label: "序号",
        width: "60px",
      },
      {
        prop: "name",
        label: "项目名称",
        width: "200px",
      },
      {
        prop: "code",
        label: "项目编码",
      },
      {
        prop: "specimenTypeId",
        label: "标本名称",
        render: ({ row }) => {
          const patientType = data.listcategoryOptions ?? [];
          let resText = row.specimenTypeId;
          if (patientType && patientType.length > 0) {
            let filter = patientType.filter(
              (item) => item.value == row.specimenTypeId
            );
            if (filter && filter.length > 0) {
              resText = filter[0].label;
            }
          }
          return h("div", resText);
        },
      },
      {
        prop: "tubeId",
        label: "试管名称",
        width: "200px",
        render: ({ row }) => {
          let resText = row.tubeId;
          return h(
            "div",
            {
              style: {
                width: "50%",
                background: row.tubeColor,
                marginLeft: "25%",
              },
            },
            resText
          );
        },
      },
      {
        prop: "createTime",
        label: "创建时间",
        format: "datetime",
      },
      {
        label: "操作",
        actions: [{ event: "cancel", label: "取消关联", type: "danger" }],
      },
    ],
    onAct: onPageActions,
    onPaginate: (pagination: QueryPagination) =>
      request("tableData", pagination),
    highlightCurrentRow: true,
    onRowClick: (row: any) => {
      selectEquipment.value = row;
    },
  };
  return tableProps;
});

const editFormProps = computed<EditFormProps>(() => {
  const formItems: FormItemProps[] = [
    {
      prop: "name",
      label: "项目名称",
      required: true,
    },
    {
      prop: "searchCode",
      label: "检索码",
      required: false,
    },
    {
      prop: "officeId",
      label: "科室名称",
      required: false,
      as: "select",
      options: {
        loadMethod: () => $api.upms.org.listAsOptions(),
      },
    },
    {
      prop: "price",
      label: "价格",
      required: false,
    },
    {
      prop: "specimenTypeId",
      label: "标本",
      required: false,
      as: "select",
      options: {
        loadMethod: $api.lis.specimen.category.listAsOptions,
      },
    },
    {
      prop: "tubeId",
      label: "试管",
      required: false,
      as: "select",
      options: {
        loadMethod: $api.lis.tube.listAsOptions,
      },
    },
    {
      prop: "projectType",
      label: "项目类别",
      required: false,
      as: "select",
      options: {
        loadMethod: () => {
          return [
            {
              label: "检验",
              value: 0,
            },
            {
              label: "检查",
              value: 1,
            },
          ];
        },
      },
    },
    {
      prop: "templateId",
      label: "项目模板",
      required: false,
      as: "select",
      options: {
        loadMethod: () =>
          $api.emr.emrType.list("e0669fbb0f5cd2cbab0912ecee3cd6c3"),
      },
    },
    {
      prop: "whether",
      label: "是否启用",
      as: "switch",
      options: {
        activeValue: 1,
        inactiveValue: 0,
      },
    },
    {
      prop: "outward",
      label: "是否外送",
      as: "switch",
      options: {
        activeValue: 1,
        inactiveValue: 0,
      },
    },
  ];

  const editProps: EditFormProps = {
    model: editingObj.value,
    items: formItems,
    columns: 1,
    size: "mini",
    onClose: () => {
      editingObj.value = null;
    },
    onCancel: () => {
      editingObj.value = null;
    },
    onValidate: (model) => {
      request("save", model);
    },
  };

  return editProps;
});

const onPageActions = (action: IAction, model?: any) => {
  switch (action.event) {
    case "add":
    case "edit":
      editingObj.value = $api.lis.portfolioProject.$$createEntity(model);
      break;
    case "destroy":
      request("destroy", model ? model.id : "");
      break;
    case "relation":
      if (!props.selectEquipment?.id) {
        $notify.warning("请先选择仪器字典");
        break;
      }
      modelValue.value = true;
      break;
    case "cancel":
      if (!model) {
        $notify.error("请选择需要取消关联的检验项目");
        return;
      }
      const projectIdData = [].concat(model).map((item) => {
        return item.id;
      });
      request("cancelDeviceRelatedPortfolioProjects", {
        deviceId: props.selectEquipment?.id ?? "",
        portfolioProjectIdList: projectIdData,
      });
  }
};

watch(
  () => props.selectEquipment,
  (item) => {
    if (item && item.id) {
      request("listAsOptions");
      request("listcategoryOptions");
      request("tableData");
    }
  },
  {
    immediate: true,
  }
);
</script>

<style lang="less" scoped></style>
